package com.dpj.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/*
  the problem of starvation ,two Threads do the same thing in the meanwhile
  so they can't going on.
  the solution is that we should device them into different kinds of Thread pool

  Attention ,it's not the deadlock, they are similar,but they are not the same,
  they are just waiting,but don't lock
 */
@Slf4j(topic = "c.TestStarvation")
public class TestStarvation {


       static   final  List<String> MENU = Arrays.asList("orange","grapefruit","banana","sugar cane");
       static Random random=new Random();
       static String cooking(){
           return   MENU.get(random.nextInt(MENU.size()));
       }

    public static void main(String[] args) {
        ExecutorService waiter = Executors.newFixedThreadPool(1);
        ExecutorService provider = Executors.newFixedThreadPool(1);
        waiter.execute(()->{
            log.debug("processing order");
            Future<String> order_fruit =provider.submit(() -> {
                log.debug("order fruit");
                return "done";
            });
            try {
                log.debug("the fruit is coming {}",order_fruit.get() );
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });

        waiter.execute(()->{
            log.debug("processing order");
            Future<String> order_fruit = provider.submit(() -> {
                log.debug("order fruit");
                return "done";
            });
            try {
                log.debug("the fruit is coming {}",order_fruit.get() );
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
    }

}
